<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>webgpu</title>
    <style>
      .container{
        display: flex;
        gap: 4px
      }
      canvas{
        background-color: #ccc;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <canvas id="canvas1" width="20" height="20"></canvas>
    </div>
    <script type="module">
      import { vertex, fragment } from "./shader/shader.js";
      import { vec3, mat4 } from './gl-matrix/esm/index.js'; 

      const canvas = document.querySelector("#canvas1");
      const context = canvas.getContext("webgpu");

      const requestAdapter = await navigator.gpu.requestAdapter();
      const device = await requestAdapter.requestDevice();
      const format = navigator.gpu.getPreferredCanvasFormat();
      context.configure({
        device,
        format,
      });

      const vertexArray = new Float32Array([
        1.0, 0.0, 0.0, 
        0.0, 1.0, 0.0, 
        0.0, 0.0, 1.0,
      ]);

      const vertexBuffer = device.createBuffer({
        size: vertexArray.byteLength,
        usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
      });

      const renderPipeline = device.createRenderPipeline({
        layout: "auto",
        vertex: {
          module: device.createShaderModule({ code: vertex }),
          entryPoint: "main",
          buffers: [
            {
              arrayStride: 3 * 4,
              attributes: [
                {
                  shaderLocation: 0,
                  format: "float32x3",
                  offset: 0,
                },
              ],
            },
          ],
        },
        fragment: {
          module: device.createShaderModule({ code: fragment }),
          entryPoint: "main",
          targets: [
            {
              format: format,
            },
          ],
        },
        primitive: {
          topology: "triangle-strip",
        },
      });
      
      const render = () => {
        device.queue.writeBuffer(vertexBuffer, 0, vertexArray);

        const commandEncoder = device.createCommandEncoder();
        const renderPass = commandEncoder.beginRenderPass({
          colorAttachments: [
            {
              view: context.getCurrentTexture().createView(),
              storeOp: "store",
              loadOp: "clear",
              clearValue: { r: 0.5, g: 0.5, b: 0.5, a: 1.0 }, //背景颜色
            },
          ],
        });
        renderPass.setPipeline(renderPipeline);
        renderPass.setVertexBuffer(0, vertexBuffer);
        renderPass.draw(3);
        renderPass.end();
        device.queue.submit([commandEncoder.finish()]);

        requestAnimationFrame(render);
      };
      render();
    </script>
  </body>
</html>
